package com.tntsl.test;

import android.Manifest;
import android.content.ContentProviderClient;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission();
    }

    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            // 显示申请权限界面
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {

            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
        } else {
            readContacts();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            readContacts();
        }
    }

    public void readContacts() {
        ContentProviderClient contentProviderClient = getContentResolver().acquireContentProviderClient(ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
        String[] projection = new String[]{"display_name", "data1"};
        try {
            Cursor cursor = contentProviderClient.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null);
            while (cursor.moveToNext()) {
                String name = cursor.getString(0);
                String mobile = cursor.getString(1);
                System.out.println(name + "：" + mobile);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

}
